/**
 ----------------------
 1.整张表的增删改查
 2.逻辑复用
 ----------------------
 */
import {useUploadFile} from '@/utils/file/file';
import {testFormConfig} from './form';
import {testTable} from './table';
import {
    deleteTest,
    fetchTestById,
    fetchTestList,
    exportTest,
    importTest,
} from '@/api/modules/ax/test/test';
import {response} from '@/utils/table/table';
import {setContextMenu} from '@/views/components/contextmenu/data';
import type {AxTest} from '@/api/modules/ax/test/types';
/**
 * @description: 根据条件获取列表数据
 */
export const testList = async () => {
    try {
            testTable.value.loading = true;
        const {data} = await fetchTestList(testTable.value.query);
            testTable.value.data = data.rows;
            testTable.value.query.total = data.total;
            testTable.value.loading = false;
    } catch (error) {
            testTable.value.loading = false;
    }
};

/**
 * @description: 根据ID查询数据,并打开表单页面
 * @param {number} id
 */
export const testEdit = async (id?: number) => {
    let targetId: number | string = id ? id : testTable.value.keys[0];
        testTable.value.loading = true;
    const {data} = await fetchTestById(targetId);
    if (data.data) {
            testFormConfig.value.form = data.data;
            testFormConfig.value.display = true;
    }
        testTable.value.loading = false;
};

/**
 * @description:
 * 清空表单所有内容
 * 打开表单页面
 */
export const testCreate = async () => {
        testFormConfig.value.display = true;
        testFormConfig.value.reset!();
};

export const testDelete = async (id?: number) => {
    let ids = id ? [id] : testTable.value.keys;
    await response(deleteTest, ids);
    await testList();
        testTable.value.keys = [];
};

// 导出EXCEL文件
export const testExport = () => {
    return exportTest(testTable.value.query);
};

/**
 * @description:搜索
 * 需要将页码设为第一页，避免翻页后搜不到内容
 */
export const testSearch = () => {
        testTable.value.query.pageNum = 1;
        testList();
};

/**
 * @description: 使用excel导入文件
 */
export const testImport = async () => {
    const files = await useUploadFile({
        accept: '.xls, .xlsx',
    });
    importTest(files[0]);
};

/**
 * @description:
 *  显示右键菜单
 *  在表格和卡片中复用
 * @param {AxTest} item
 */
export const displayTestMenu = (item: AxTest) => {
        testFormConfig.value.form = item;
        testTable.value.keys = [item.testId];
    setContextMenu({
        items: testTable.value.contextmenu,
    });
};
